@{
    Layout = "_Layout";
    ViewData["Title"] = "情话内容";
}

<el-container>
    <avue-crud ref="crud" :data="tableData" :option="option" :permission="hasPermission" :page.sync="pageOption" :table-loading="loading"
               v-on:refresh-change="refreshChange"
               v-on:row-save="handleRowSave"
               v-on:row-update="handleRowUpdate"
               v-on:row-del="handleRowDel"
               v-on:search-change="searchChange"
               v-on:search-reset="resetChange"
               :cell-style="cellStyle"
               v-on:on-load="onLoad">
        <template slot="menuLeft">
            <el-button type="primary" icon="el-icon-download" :size="size"
                       @@click="handleDownloadTemplate"
                       :loading="downloadLoading">
                下载模板
            </el-button>
            <el-button type="success" icon="el-icon-upload2" :size="size"
                       @@click="handleImportDialog">
                导入内容
            </el-button>
        </template>
        <template slot="record" slot-scope="scope">
            <modify-record :data="scope.row"></modify-record>
        </template>
    </avue-crud>
    
            <el-dialog title="导入内容数据" :visible.sync="importDialogVisible" width="500px" :close-on-click-modal="false">
                <el-alert title="导入说明" type="info" :closable="false" style="margin-bottom: 15px;">
                    <div>1. 请先下载模板，按模板格式填写数据</div>
                    <div>2. 仅支持.xlsx格式Excel文件</div>
                    <div>3. 分类名称和内容为必填字段</div>
                    <div>4. 导入后数据默认状态为启用</div>
                </el-alert>

                <el-upload class="upload-demo"
                           ref="upload"
                           action=""
                           :auto-upload="false"
                           :on-change="handleFileChange"
                           :file-list="fileList"
                           accept=".xlsx"
                           :limit="1">
                    <el-button slot="trigger" :size="size" type="primary">选择文件</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传Excel文件(.xlsx)，且不超过10MB</div>
                </el-upload>

        <div slot="footer" class="dialog-footer">
            <el-button @@click="importDialogVisible = false" :size="size">取消</el-button>
            <el-button type="primary" :loading="importLoading" @@click="handleImport" :size="size">开始导入</el-button>
        </div>
    </el-dialog>
</el-container>

@section Scripts {
    <script src="/ruoveaui/xg6rvft8p/avue/filesaver.min.js"></script>
    <script src="/ruoveaui/xg6rvft8p/avue/xlsx.full.min.js"></script>
    <script>
        new Vue({ 
            mixins: [curdMixin],
            data() {
                return {
                    size:formOption.size,
                    themeV: localStorage.getItem('themeV'),
                    name: "content",
                    pageUrl: `/content/pages`,
                    addUrl: `/content/add`,
                    editUrl: `/content/update`,
                    deleteUrl: `/content/delete`,
                    importDialogVisible: false,
                    downloadLoading: false,
                    importLoading: false,
                    fileList: [],

                    option: {
                        searchShowBtn: Permissions.avePermission(`content:searchBtn`),
                        refreshBtn: Permissions.avePermission(`content:searchBtn`),
                        menuWidth: '350',
                        rowKey: 'id',
                        searchShow: false,
                        column: [
                            { prop: "id", label: `${this.i18n.t('primary_key')}`, search: false, hide: true, type: "number", display: false, showColumn: false },
                            { prop: "categoryId", label: `分类`, search: true, hide: false, width: '150', type: 'select', dicUrl: '/category/list', dicMethod: 'post',props: {res: 'data.rows',label: 'name',value: 'id' }, dicQuery: {}, dicKey: 'id', dicLabel: 'name', rules: [{ required: true, message: `请选择分类`, trigger: 'blur' }] },
                            { prop: "content", label: `内容`, search: true, hide: false, type: 'textarea', minRows: 3, maxRows: 6, span: 24,   rules: [{ required: true, message: `请输入内容`, trigger: 'blur' }] },
                            { prop: "isDisable", label: `${this.i18n.t('status')}`, search: true, hide: false, value: 0, type: "radio", button: true, dicData: disableDicData, width: '100' },
                            { prop: "record", label: `${this.i18n.t('modification_record')}`, slot: true, display: false, showColumn: false, width: 140, align: `center` },
                        ],
                    },

                }
            },
            created() {
                this.selectRow = {};
            },
            methods: {
                // 生成固定的颜色（基于ID）
                getColorByCategoryId(categoryId) {
                    // 使用简单的哈希函数将ID转换为颜色
                    const colors = [
                        '#409EFF', '#67C23A', '#E6A23C', '#F56C6C', 
                        '#909399', '#8BC34A', '#FF9800', '#E91E63',
                        '#9C27B0', '#3F51B5', '#00BCD4', '#009688'
                    ];
                    // 确保categoryId是数字并计算索引
                    const index = Math.abs(parseInt(categoryId || 0)) % colors.length;
                    return colors[index];
                },
                
                cellStyle({ row, column, rowIndex, columnIndex }) {
                    // 状态列样式
                    if (columnIndex == 3) {
                        if (row.isDisable == 0) {
                            return { color: '#409eff' }
                        } else {
                            return { color: '#f56c6c' }
                        }
                    }
                    // 分类列样式（columnIndex为1，对应分类列）
                    if (columnIndex == 1 && row.categoryId) {
                        const color = this.getColorByCategoryId(row.categoryId);
                        return {
                            color: color,
                            fontWeight: 'bold'
                        };
                    }
                },
                
                // 下载导入模板
                async handleDownloadTemplate() {
                    try {
                        this.downloadLoading = true;
                        
                        // 创建Excel工作簿
                        const wb = XLSX.utils.book_new();
                        
                        // ========== 数据Sheet ==========
                        // 创建数据sheet内容
                        const dataSheet = [
                            ['分类名称*', '内容*'], // 表头
                            ['分类示例', '内容示例']  // 示例数据
                        ];
                        
                        // 将数据添加到数据sheet
                        const wsData = XLSX.utils.aoa_to_sheet(dataSheet);
                        
                        // 设置列宽
                        wsData['!cols'] = [{ wch: 20 }, { wch: 60 }];
                        
                        // 将数据sheet添加到工作簿
                        XLSX.utils.book_append_sheet(wb, wsData, '数据填写');
                        
                        // ========== 导入说明Sheet ==========
                        // 创建导入说明内容
                        const instructionContent = [
                            ['导入说明'],
                            [''],
                            ['1. 带*的字段为必填字段'],
                            ['2. 分类名称必须是系统中存在的分类'],
                            ['3. 导入后数据默认状态为启用'],
                            ['4. 请勿修改表头名称'],
                            ['5. 删除示例数据后填入实际数据'],
                            [''],
                            ['可用分类列表:']
                        ];
                        
                        // 获取可用分类列表
                        try {
                            // 使用已配置好的axios实例发起请求
                            const data = await this.$http.post('/category/list');
                            
                            // axios拦截器已经处理了成功和错误的情况，这里直接使用返回的数据
                            if (data.rows && data.rows.length > 0) {
                                data.rows.forEach(category => {
                                    if (category.isDisable === 0) { // 只显示启用的分类
                                        instructionContent.push([category.name]);
                                    }
                                });
                            } else {
                                instructionContent.push(['获取分类列表失败，请手动添加']);
                            }
                        } catch (err) {
                            console.warn('获取分类列表失败:', err);
                            instructionContent.push(['获取分类列表失败，请手动添加']);
                        }
                        
                        // 创建说明sheet
                        const wsInstruction = XLSX.utils.aoa_to_sheet(instructionContent);
                        
                        // 设置列宽
                        wsInstruction['!cols'] = [{ wch: 40 }];
                        
                        // 将说明sheet添加到工作簿
                        XLSX.utils.book_append_sheet(wb, wsInstruction, '导入说明');
                        
                        // 生成Excel文件并下载
                        const fileName = `内容导入模板_${new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)}.xlsx`;
                        XLSX.writeFile(wb, fileName);
                        
                        this.$message.success('模板下载成功');
                    } catch (error) {
                        console.error('下载模板错误:', error);
                        this.$message.error('模板下载失败');
                    } finally {
                        this.downloadLoading = false;
                    }
                },
                
                // 打开导入对话框
                handleImportDialog() {
                    this.importDialogVisible = true;
                    this.fileList = [];
                },
                
                // 处理文件选择变化
                handleFileChange(file, fileList) {
                    this.fileList = fileList.slice(-1);
                },
                // 处理导入
                async handleImport() {
                    if (!this.fileList || this.fileList.length === 0) {
                        this.$message.warning('请选择要导入的文件');
                        return;
                    }
                    
                    try {
                        this.importLoading = true;
                        const file = this.fileList[0].raw;
                        
                        // 验证文件类型
                        const allowedExtensions = ['.xlsx'];
                        const fileExtension = file.name.split('.').pop().toLowerCase();
                        if (!allowedExtensions.includes('.' + fileExtension)) {
                            this.$message.error('请上传Excel文件(.xlsx格式)');
                            return;
                        }
                        
                        // 创建FormData
                        const formData = new FormData();
                        formData.append('file', file);
                        
                        // 发送请求
                        // 使用已配置好的axios实例发起请求，表单数据不需要设置Content-Type，axios会自动处理
                        await this.$http.post('/content/import', formData)
                        .then(data => {
                            // axios拦截器已经处理了成功和错误的情况
                            this.$message.success(`导入成功${data.successCount}条，失败${data.failCount}条，重复数据${data.duplicateCount}条（已跳过）`);
                            this.importDialogVisible = false;
                            // 刷新表格数据
                            this.onLoad();
                        }).catch(error => {
                            this.importDialogVisible = false;
                        });
                        
                        
                    } catch (error) {
                        console.error('导入错误:', error);
                        this.$message.error(error.message || '导入失败');
                    } finally {
                        this.importLoading = false;
                    }
                },
            }
        });
    </script>

}